<template>
  <div>
    <!-- 查询条件 -->
    <el-form :inline="true" :model="queryData" class="query-form">
      <el-form-item label="品牌名称">
        <el-input v-model="queryData.brandName" placeholder="请输入品牌名称" />
      </el-form-item>
      <el-form-item label="品牌描述">
        <el-input v-model="queryData.brandDesc" placeholder="请输入品牌描述" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getBrand">查询</el-button>
        <el-button type="success" @click="addDialogVisible = true">新增品牌</el-button>
      </el-form-item>
    </el-form>

    <!-- 品牌数据表格 -->
    <el-table :data="brands" style="width: 100%" border stripe>
      <el-table-column align="center" prop="brandId" label="品牌ID" width="100" />
      <el-table-column align="center" prop="brandName" label="品牌名称" width="150" />
      <el-table-column align="center" label="Logo" width="120">
        <template #default="scope">
          <img :src="scope.row.logoUrl" style="width: 50px; height: 50px; border-radius: 50%;" alt="logo" />
        </template>
      </el-table-column>

      <el-table-column align="center" prop="brandDesc" label="品牌描述" width="240" />

      <el-table-column align="center" prop="status" label="状态" width="120">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              @change="(status) => handleStatusChange(scope.row.brandId, status)"
          />
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column label="更新时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.updateTime) }}
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column align="center" label="操作" width="180">
        <template #default="scope">
          <el-button type="info" @click="handleEditBrand(scope.row)">编辑</el-button>
          <el-button type="danger" @click="handleDeleteBrand(scope.row.brandId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        style="margin-top: 20px; text-align: center;"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page.sync="queryData.pageNum"
        :page-size.sync="queryData.pageSize"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
    />

    <!-- 编辑品牌弹窗 -->
    <el-dialog
        title="编辑品牌信息"
        v-model="editDialogVisible"
        width="500px"
        @close="editDialogVisible = false"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="品牌名称">
          <el-input v-model="editForm.brandName" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌描述">
          <el-input v-model="editForm.brandDesc" placeholder="请输入品牌描述" />
        </el-form-item>

        <el-form-item label="Logo">
          <img :src="editForm.logoUrl" style="width: 100px;" alt="logo" />
        </el-form-item>

        <el-form-item label="状态">
          <el-switch
              v-model="editForm.status"
              :active-value="1"
              :inactive-value="0"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          />
        </el-form-item>
      </el-form>
      <div style="text-align: right; margin-top: 20px;">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateBrand">保存</el-button>
      </div>
    </el-dialog>

    <!-- 新增品牌弹窗 -->
    <el-dialog
        title="新增品牌"
        v-model="addDialogVisible"
        width="500px"
        @close="addDialogVisible = false"
    >
      <el-form :model="addForm" label-width="80px">
        <el-form-item label="品牌名称" required>
          <el-input v-model="addForm.brandName" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌描述" required>
          <el-input v-model="addForm.brandDesc" placeholder="请输入品牌描述" />
        </el-form-item>
        <el-form-item label="Logo" required>
          <el-upload
              class="upload-demo"
              action="" <!-- 确保配置上传地址或处理上传逻辑 -->
          :before-upload="beforeUpload"
          :file-list="[]"
          :auto-upload="false"
          :on-change="(file, fileList) => { addForm.logoFile = file.raw }"
          :on-remove="() => { addForm.logoFile = null }"
          >
          <el-button type="primary">点击上传Logo</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
              v-model="addForm.status"
              :active-value="1"
              :inactive-value="0"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          />
        </el-form-item>
      </el-form>
      <div style="text-align: right; margin-top: 20px;">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddBrand">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import {
  getBrands,
  getBrandInfo,
  updateBrandStatus,
  updateBrand,
  deleteBrand,
  addBrand
} from '@/api/brand';
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatDate } from '@/utils/format.js';

// 响应式数据
const brands = ref([]);
const total = ref(0);

const queryData = ref({
  pageNum: 1,
  pageSize: 5,
  brandName: '',
  brandDesc: '',
});

const editDialogVisible = ref(false);
const editForm = ref({
  brandId: '',
  brandName: '',
  brandDesc: '',
  logoUrl: '',
  status: 1
});

const addDialogVisible = ref(false);
const addForm = ref({
  brandName: '',
  brandDesc: '',
  logoFile: null,
  status: 1
});

// 获取品牌数据
const getBrand = async () => {
  try {
    const response = await getBrands(queryData.value);
    if (response.data.code === 200) {
      brands.value = response.data.data.records;
      total.value = response.data.data.total;
    } else {
      ElMessage.error('获取品牌数据失败');
    }
  } catch (error) {
    ElMessage.error('请求错误，请稍后重试');
  }
};

// 修改状态
const handleStatusChange = async (brandId, status) => {
  try {
    const response = await updateBrandStatus(brandId, status);
    if (response.data.code === 200) {
      ElMessage.success('状态更新成功');
      getBrand();
    } else {
      ElMessage.error('状态更新失败');
    }
  } catch (error) {
    ElMessage.error('请求错误，请重试');
  }
};

// 删除品牌
const handleDeleteBrand = (brandId) => {
  ElMessageBox.confirm(
      '确认删除该品牌吗？此操作不可撤销。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        try {
          const response = await deleteBrand(brandId);
          if (response.data.code === 200) {
            ElMessage.success('删除成功');
            getBrand();
          } else {
            ElMessage.error('删除失败');
          }
        } catch (error) {
          ElMessage.error('请求错误，请重试');
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
};

// 编辑品牌
const handleEditBrand = async (brand) => {
  try {
    const response = await getBrandInfo(brand.brandId);
    if (response.data.code === 200) {
      editForm.value = { ...response.data.data };
      editDialogVisible.value = true;
    } else {
      ElMessage.error('获取品牌信息失败');
    }
  } catch (error) {
    ElMessage.error('请求错误，请稍后重试');
  }
};

// 提交更新品牌信息
const handleUpdateBrand = async () => {
  try {
    const response = await updateBrand(editForm.value);
    if (response.data.code === 200) {
      ElMessage.success('品牌信息更新成功');
      editDialogVisible.value = false;
      getBrand();
    } else {
      ElMessage.error('品牌信息更新失败');
    }
  } catch (error) {
    ElMessage.error('请求错误，请稍后重试');
  }
};

// 新增品牌
const handleAddBrand = async () => {
  try {
    if (!addForm.value.brandName || !addForm.value.brandDesc || !addForm.value.logoFile) {
      ElMessage.error('请填写所有必填项并上传Logo');
      return;
    }

    const formData = new FormData();
    formData.append('brandName', addForm.value.brandName);
    formData.append('brandDesc', addForm.value.brandDesc);
    formData.append('status', addForm.value.status);
    formData.append('logoFile', addForm.value.logoFile);

    const response = await addBrand(formData);
    if (response.data.code === 200) {
      ElMessage.success('新增品牌成功');
      addDialogVisible.value = false;
      // 重置表单
      addForm.value = {
        brandName: '',
        brandDesc: '',
        logoFile: null,
        status: 1
      };
      getBrand();
    } else {
      ElMessage.error('新增品牌失败');
    }
  } catch (error) {
    ElMessage.error('请求错误，请稍后重试');
  }
};

// 处理文件上传前的钩子
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB');
  }
  return isImage && isLt2M;
};

// 监听上传成功事件
const handleUploadSuccess = (response, file, fileList) => {
  if (response.data.code === 200) {
    addForm.value.logoUrl = response.data.data.logoUrl;
    addForm.value.logoFile = file.raw;
  } else {
    ElMessage.error('上传Logo失败');
  }
};

// 页码变化事件
const handlePageChange = (newPage) => {
  queryData.value.pageNum = newPage;
  getBrand();
};

// 每页条数变化事件
const handleSizeChange = (newSize) => {
  queryData.value.pageSize = newSize;
  queryData.value.pageNum = 1;
  getBrand();
};

onMounted(() => {
  getBrand();
});
</script>
